package com.ruoyi.common.utils.http;

import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpClientUtils {
    private static ClientConnectionManager connectionManager = null;
    private static HttpParams httpParams = null;
    private static final String HTTPS = "https";

    static {
        httpParams = new BasicHttpParams();
        ConnManagerParams.setMaxTotalConnections(httpParams, 100);
        ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(50));
        HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
        HttpConnectionParams.setSoTimeout(httpParams, 300000);
        SchemeRegistry schreg = new SchemeRegistry();
        schreg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schreg.register(new Scheme(HTTPS, SSLSocketFactory.getSocketFactory(), 443));
        connectionManager = new ThreadSafeClientConnManager(httpParams, schreg);
    }

    /**
     * Return a new httpClient using default configuration parameters.
     *
     * @return A new HttpClient object.
     */
    public static HttpClient getHttpClient() {
        return new DefaultHttpClient(connectionManager, httpParams);
    }

    /**
     * get response by post method
     *
     * @param httpClient
     * @param url
     * @param paramsMap
     * @return
     */
    private static String getResponseByPost(HttpClient httpClient, String url, Map<String, String> paramsMap,
                                            String requestXML, Map<String, String> headerMap) {
        HttpPost httpPost = new HttpPost(url);
        try {
            //add params
            if (null != paramsMap && paramsMap.size() > 0) {
                List<NameValuePair> nvps = new ArrayList<>();
                for (String name : paramsMap.keySet()) {
                    nvps.add(new BasicNameValuePair(name, paramsMap.get(name)));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            } else {
                StringEntity reqEntity = new StringEntity(requestXML);
                httpPost.setEntity(reqEntity);
            }

            //add http header
            if (null != headerMap && headerMap.size() > 0) {
                List<Header> headers = new ArrayList<>();
                for (String name : headerMap.keySet()) {
                    Header header = new BasicHeader(name, headerMap.get(name));
                    headers.add(header);
                }
                httpPost.setHeaders(headers.toArray(headers.toArray(new Header[headers.size()])));
            }

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String output = "";
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode() && null != entity) {
                output = EntityUtils.toString(entity);
            }
            if (null != entity) {
                // call the HttpEntity#consumeContent() method to consume any available content on the stream. HttpClient
                // will automatically release the underlying connection back to the connection manager as soon as it
                // detects that the end of the content stream has been reached.
                entity.consumeContent();
            }
            return output;
        } catch (Exception e) {
            httpPost.abort();
            return null;
        }
    }

    public static String doPost(String url, Map map){
        return HttpClientUtils.getResponseByPost(HttpClientUtils.getHttpClient(), url, map, null, new HashMap<>());
    }

    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("username", "tj001@hnac");
        map.put("password", "123456");
        try {
            String result = HttpClientUtils.doPost("https://tj.angchengls.com/osapi/Login/Loginact", map);
            System.out.println(result);
        } catch (Exception e) {

        }
    }
}
